#!/bin/bash
# File: gadt-mkhtml
# Summary: This is a ...
# Author: yetist <yetist@gmail.com>
# Version: 2009-10-07 18:48:25
# 
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

CLEANCACHE=0
CLEANUP=0
EDITSGML=0
FUZZY=0
INSTALL=0
TARBALL=0
LIST=0
LOGGING=0
MERGEPO=0
NOBUILD=0
NOCONFIGURE=0
NOEXTRACT=0
NOHTMLHELP=0
NOUPDATEXML=0
NOBROWSER=1
REVIEWALLSGML=0
BUILDSCRIPT="build.rc"
COLORMSG=0

plain() {
	local mesg=$1; shift
	if [ $COLORMSG -eq 1 ]; then
		printf "\033[1;1m    ${mesg}\033[1;0m\n" "$@" >&2
	else
		printf "    ${mesg}\n" "$@" >&2
	fi
}

msg() {
	local mesg=$1; shift
	if [ $COLORMSG -eq 1 ]; then
		printf "\033[1;32m==>\033[1;0m\033[1;1m ${mesg}\033[1;0m\n" "$@" >&2
	else
		printf "==> ${mesg}\n" "$@" >&2
	fi
}

msg2() {
	local mesg=$1; shift
	if [ $COLORMSG -eq 1 ]; then
		printf "\033[1;34m  ->\033[1;0m\033[1;1m ${mesg}\033[1;0m\n" "$@" >&2
	else
		printf "  -> ${mesg}\n" "$@" >&2
	fi
}

warning() {
	local mesg=$1; shift
	if [ $COLORMSG -eq 1 ]; then
		printf "\033[1;33m==> $(gettext "WARNING:")\033[1;0m\033[1;1m ${mesg}\033[1;0m\n" "$@" >&2
	else
		printf "==> $(gettext "WARNING:") ${mesg}\n" "$@" >&2
	fi
}

error() {
	local mesg=$1; shift
	if [ $COLORMSG -eq 1 ]; then
		printf "\033[1;31m==> $(gettext "ERROR:")\033[1;0m\033[1;1m ${mesg}\033[1;0m\n" "$@" >&2
	else
		printf "==> $(gettext "ERROR:") ${mesg}\n" "$@" >&2
	fi
}


##
# Special exit call for traps, Don't print any error messages when inside,
# the fakeroot call, the error message will be printed by the main call.
##
trap_exit() {
	if [ "$INFAKEROOT" -eq 0 ]; then
		echo
		error "$@"
	fi
	exit 1
}


usage() {
	printf "gadt-mkhtml %s\n" "$Revision: 380 $"
	echo
	printf "Usage: %s [options]\n" "$0"
	echo
	echo "Options:"
	echo "  -c, --clean          Clean up work files after build"
	echo "  -b, --browser        Call browser to view the html file when exit"
	echo "  -C, --cleancache     Clean up source files from the cache"
	echo "  -e, --noextract      Do not extract source files (use existing src/ dir)"
	echo "  -f, --fuzzy          Use fuzzy item in po file (Unsafe)"
	echo "  -h, --help           This help"
	echo "  -i, --install        Install the html document to the system, so devhelp can show it"
	echo "  -L, --log            Log package build process"
	echo "  -l, --list           List all files"
	echo "  -o, --nobuild        Download and extract files only"
	echo "  -s, --noupdatexml    Do not update the xml files"
	echo "  -H, --nohtmlhelp     Do not create htmlhelp file"
	echo "  -r, --reviewsgml     Review all sgml files"
	echo "  -t, --editsgml       Edit your sgml file"
	echo "  -T, --tarball        Create tarball for release"
	echo "  -m, --mergepo        Merge youre po to master po file"
	echo "  -n, --noconfigure     Do not configure the source"
	printf "  -p <buildscript> Use an alternate build script (instead of '%s')\n" "$BUILDSCRIPT"
	echo
}

# getopt like parser
parse_options() {
	local short_options=$1; shift;
	local long_options=$1; shift;
	local ret=0;
	local unused_options=""

	while [ -n "$1" ]; do
		if [ ${1:0:2} = '--' ]; then
			if [ -n "${1:2}" ]; then
				local match=""
				for i in ${long_options//,/ }; do
					if [ ${1:2} = ${i//:} ]; then
						match=$i
						break
					fi
				done
				if [ -n "$match" ]; then
					if [ ${1:2} = $match ]; then
						printf ' %s' "$1"
					else
						if [ -n "$2" ]; then
							printf ' %s' "$1"
							shift
							printf " '%s'" "$1"
						else
							echo "gadt-mkhtml: option '$1' requires an argument" >&2
							ret=1
						fi
					fi
				else
					echo "gadt-mkhtml: unrecognized option '$1'" >&2
					ret=1
				fi
			else
				shift
				break
			fi
		elif [ ${1:0:1} = '-' ]; then
			for ((i=1; i<${#1}; i++)); do
				if [[ "$short_options" =~ "${1:i:1}" ]]; then
					if [[ "$short_options" =~ "${1:i:1}:" ]]; then
						if [ -n "${1:$i+1}" ]; then
							printf ' -%s' "${1:i:1}"
							printf " '%s'" "${1:$i+1}"
						else
							if [ -n "$2" ]; then
								printf ' -%s' "${1:i:1}"
								shift
								printf " '%s'" "${1}"
							else
								echo "gadt-mkhtml: option requires an argument -- '${1:i:1}'" >&2
								ret=1
							fi
						fi
						break
					else
						printf ' -%s' "${1:i:1}"
					fi
				else
					echo "gadt-mkhtml: invalid option -- '${1:i:1}'" >&2
					ret=1
				fi
			done
		else
			unused_options="${unused_options} '$1'"
		fi
		shift
	done

	printf " --"
	if [ -n "$unused_options" ]; then
		for i in ${unused_options[@]}; do
			printf ' %s' "$i"
		done
	fi
	if [ -n "$1" ]; then
		while [ -n "$1" ]; do
			printf " '%s'" "${1}"
			shift
		done
	fi
	printf "\n"

	return $ret
}

ARGLIST=$@

# Parse Command Line Options.
OPT_SHORT="bcCefhHilLmnop:rstT"
OPT_LONG="browser,clean,cleancache,fuzzy,editsgml,reviewsgml,list,mergepo,install,nodeps,noextract,noconfigure,noupdatexml,nohtmlhelp,help,log,tarball,nobuild"
# Options
OPT_TEMP="$(parse_options $OPT_SHORT $OPT_LONG "$@" || echo 'PARSE_OPTIONS FAILED')"
#OPT_TEMP="$(getopt -o "$OPT_SHORT" -l "$OPT_LONG" -n "$(basename "$0")" -- "$@" || echo 'PARSE_OPTIONS FAILED')"
if echo "$OPT_TEMP" | grep -q 'PARSE_OPTIONS FAILED'; then
	# This is a small hack to stop the script bailing with 'set -e'
	echo; usage; exit 1 # E_INVALID_OPTION;
fi
eval set -- "$OPT_TEMP"
unset OPT_SHORT OPT_LONG OPT_TEMP



while true; do
	case "$1" in
		# Makepkg Options
		-b|--browser)       NOBROWSER=0;;
		-C|--cleancache)  CLEANCACHE=1 ;;
		-H|--nohtmlhelp)      NOHTMLHELP=1 ;;
		-L|--log)         LOGGING=1 ;;
		-V|--version)     version; exit 0 ;; # E_OK
		-c|--clean)       CLEANUP=1 ;;
		-e|--noextract)   NOEXTRACT=1 ;;
		-f|--fuzzy)       FUZZY=1 ;;
		-h|--help)        usage; exit 0 ;; # E_OK
		-i|--install)      INSTALL=1 ;;
		-T|--tarball)      TARBALL=1 ;;
		-l|--list)        LIST=1 ;;
		--nocolor)     USE_COLOR='n' ;;
		-m|--mergepo)     MERGEPO=1 ;;
		-n|--noconfigure)      NOCONFIGURE=1 ;;
		-o|--nobuild)     NOBUILD=1 ;;
		-p)               shift; BUILDFILE=$1 ;;
		-r|--reviewsgml)      REVIEWALLSGML=1 ;;
		-s|--noupdatexml)     NOUPDATEXML=1 ;;
		-t|--editsgml)      EDITSGML=1 ;;

		--)               OPT_IND=0; shift; break;;
		*)                usage; exit 1 ;; # E_INVALID_OPTION
	esac
	shift
done

BUILDFILE=${BUILDFILE:-$BUILDSCRIPT}

source ./$BUILDFILE
startdir=`pwd`
pkgfile=`basename $source`
tmpdir=$startdir/tmp
srcdir=$tmpdir/$pkgname-$pkgver
source ./$BUILDFILE

# check if messages are to be printed using color
if [ -t 2 -a ! "$USE_COLOR" = "n" ]; then
	COLORMSG=1
fi

SRCDEST=${_SRCDEST:-$SRCDEST}
SRCDEST=${SRCDEST:-$tmpdir} #default to $startdir if undefined

################## init ###########################

init_pot()
{
	if [ -d $startdir/po ];
	then
		return
	else
		msg "正在初始化您的po文件..."
		mkdir $startdir/po
		gadt-po -c -p $tmpdir/pot $moddir
		if [ -f ~/.gtkdocpo ];then
			username=$(source ~/.gtkdocpo; echo $username)
		else
			username=unknown
		fi

		if [ -f $startdir/AUTHORS ]; then
			local pos=`cat $startdir/AUTHORS|grep -v "^#"| grep "^$username" |awk '{print $4}'`
			eval $pos #这将会产生po_files变量
			var=`echo $po_files |sed 's/,/ /g'`
			for i in $var;
			do 
				mname=${i%.po}
				msgmerge -N -F "$modname-$pkgver.po" $tmpdir/pot/$mname.pot 2>/dev/null| msgattrib --no-obsolete - -o $startdir/po/$mname.po
				#msg2 "正在调用google为您生成模糊翻译内容..."
				#gadt-autotrans $startdir/po/$mname.po
				text=`msgfmt --statistics $startdir/po/$mname.po -o /dev/null 2>&1`
				msg2 "文件:po/$mname.po ($text)"
			done
		fi
	fi
}

init_xmlpot()
{
	if [ -d $startdir/xmlpo ];
	then
		return
	else
		msg "正在初始化您的文档po文件..."
		mkdir $startdir/xmlpo
		gadt-xmlpo -c -p $tmpdir/xmlpot $docdir
		if [ -f ~/.gtkdocpo ];then
			username=$(source ~/.gtkdocpo; echo $username)
		else
			username=unknown
		fi

		if [ -f $startdir/AUTHORS ]; then
			local xmlpos=`cat $startdir/AUTHORS|grep -v "^#"|grep "^$username" |awk '{print $3}'`
			eval $xmlpos #这将会产生xmlpo_files变量
			var=`echo $xmlpo_files |sed 's/,/ /g'`
			for i in $var;
			do 
				mname=${i%.po}
				msgmerge -N -F "$modname-docs-$pkgver.po" $tmpdir/xmlpot/$mname.pot 2>/dev/null| msgattrib --no-obsolete - -o $startdir/xmlpo/$mname.po
				#msg2 "正在调用google为您生成模糊翻译内容..."
				#gadt-autotrans $startdir/xmlpo/$mname.po
				text=`msgfmt --statistics $startdir/xmlpo/$mname.po -o /dev/null 2>&1`
				msg2 "文件:xmlpo/$mname.po ($text)"
			done
		fi
	fi
}

init_tx_xmlpot()
{
	find $startdir/tmp/xmlpot/ -type f -exec basename {} \;|grep -v $xml_lang|grep -v fdl|while read line;do
	sec=`echo $line|tr -d "\."`
	name=${line%*t}
	echo "[$modname-reference-manual.docs-$sec]"
	echo "host = https://www.transifex.net"
	echo "source_file = tmp/xmlpot/$line"
	echo "source_lang = en"
	echo "trans.$xml_lang = xmlpo/$name"
	echo
done
}

init_tx_pot()
{
	find $startdir/tmp/pot/ -type f -exec basename {} \;|while read line;do
	sec=`echo $line|tr -d "\."`
	name=${line%*t}
	echo "[$modname-reference-manual.$sec]"
	echo "host = https://www.transifex.net"
	echo "source_file = tmp/pot/$line"
	echo "source_lang = en"
	echo "trans.$xml_lang = po/$name"
	echo
done
}

init_transifex()
{
	if [ ! -f $startdir/.tx/config ]
	then
		mkdir -p $startdir/.tx
		echo "[main]" > $startdir/.tx/config
		echo "host = http://www.transifex.net" >> $startdir/.tx/config
		echo  >> $startdir/.tx/config
		init_tx_xmlpot >> $startdir/.tx/config
		init_tx_pot >> $startdir/.tx/config
	fi
}

merge_pot()
{
	if [ ! -d $startdir/po ];
	then
		return
	else
		msg "正在合并您的po文件..."
		if [ -f ~/.gtkdocpo ];then
			username=$(source ~/.gtkdocpo; echo $username)
		else
			username=unknown
		fi

		if [ -f $startdir/AUTHORS ]; then
			local pos=`cat $startdir/AUTHORS|grep -v "^#"| grep "^$username" |awk '{print $4}'`
			eval $pos #这将会产生po_files变量
			var=`echo $po_files |sed 's/,/ /g'`
			for i in $var;
			do 
				mname=${i%.po}
				msgmerge -N -F $startdir/po/$mname.po "$modname-$pkgver.po" -o "$tmpdir/$modname-$pkgver.po.new"
				vim -d "$modname-$pkgver.po" "$tmpdir/$modname-$pkgver.po.new"
				msg2 "$mname.po [确认合并吗(Yes/No)？]"
				echo -n "请输入Yes或No:"
				read answer
				case "$answer" in
					y*|Y*) 
					cp "$tmpdir/$modname-$pkgver.po.new" "$modname-$pkgver.po"
					rm -f "$tmpdir/$modname-$pkgver.po.new"
					msg2 "$mname.po 成功合并"
					;;
					*)
					error "合并失败"
					;;
				esac
			done
		fi
	fi
}

merge_xmlpot()
{
	if [ ! -d $startdir/xmlpo ];
	then
		return
	else
		msg "正在合并您的po文件..."
		if [ -f ~/.gtkdocpo ];then
			username=$(source ~/.gtkdocpo; echo $username)
		else
			username=unknown
		fi

		if [ -f $startdir/AUTHORS ]; then
			local pos=`cat $startdir/AUTHORS|grep -v "^#"| grep "^$username" |awk '{print $3}'`
			eval $pos #这将会产生po_files变量
			var=`echo $xmlpo_files |sed 's/,/ /g'`
			for i in $var;
			do 
				mname=${i%.po}
				msgmerge -N -F $startdir/xmlpo/$mname.po "$modname-docs-$pkgver.po" -o "$tmpdir/$modname-docs-$pkgver.po.new"
				vim -d "$modname-docs-$pkgver.po" "$tmpdir/$modname-docs-$pkgver.po.new"
				msg2 "$mname.po [确认合并吗(Yes/No)？]"
				echo -n "请输入Yes或No:"
				read answer
				case "$answer" in
					y*|Y*) 
					cp "$tmpdir/$modname-docs-$pkgver.po.new" "$modname-docs-$pkgver.po"
					rm -f "$tmpdir/$modname-docs-$pkgver.po.new"
					msg2 "$mname.po 成功合并"
					;;
					*)
					error "合并失败"
					;;
				esac
			done
		fi
	fi
}

update_xml()
{
	msg "正在更新xml文件..."
	if [ -d $startdir/$modname-docs ];then
		cp -rfL $startdir/$modname-docs/* $docdir
	fi
	local now=`date +%Y年%m月%d日`
	for xml in $xml_tmpl;
	do
		online_uri="http://docs.osprg.org/book.php?book=$modname"
		tarball_uri="http://gtk-doc-cn.googlecode.com/files/$modname-docs.tar.gz"
		sed -i 's#XXXX年XX月XX日#'$now'#g' $docdir/$xml
		sed -i 's#TRANS_URI#'$trans_uri'#g' $docdir/$xml
		sed -i 's#TEAM_URI#'$team_uri'#g' $docdir/$xml
		sed -i 's#TEAM_NAME#'$team_name'#g' $docdir/$xml
		sed -i 's#ONLINE_URI#'$online_uri'#g' $docdir/$xml
		sed -i 's#TARBALL_URI#'$tarball_uri'#g' $docdir/$xml
		if [ -f $startdir/AUTHORS ];
		then
			cat $startdir/AUTHORS|grep -v "^#"|grep -v "^[[:space:]]*$"|sort|while read line;
		do 
			author=`echo $line|awk '{print $1}'`
			if [ "x$author" == "xunknown" -o "x$author" == "xfinished" ];then
				continue
			elif [ "x$author" == "xreview" ]; then
				local htmls=`echo $line|awk '{print $2}'`
				local xmls=`echo $line|awk '{print $3}'`
				local pos=`echo $line|awk '{print $4}'`
				eval $htmls
				eval $xmls
				eval $pos
				htmlvars=`echo $html_files |sed 's/,/ /g'`
				xmlvars=`echo $xmlpo_files |sed 's/,/ /g'`
				povars=`echo $po_files |sed 's/,/ /g'`
				for i in $xmlvars
				do
					local pot=`echo docs-${i}t|tr -d .`
					msgline="<para>\n po文件：<ulink type=\"http\" url=\"${trans_uri}/resource/${pot}/\">$i</ulink>, 文档页面："
					for j in $htmlvars
					do
						msgline="$msgline<ulink type=\"http\" url=\"${svnroot}/$j\">$j</ulink> "
					done
					msgline="${msgline}\n</para>\n"
					sed -i -e "/<\!-- REVIEW -->/i$msgline" $docdir/$xml
				done
				for i in $povars
				do
					local pot=`echo ${i}t|tr -d .`
					msgline="<para>\n po文件：<ulink type=\"http\" url=\"${trans_uri}/resource/${pot}/\">$i</ulink>, 文档页面："
					for j in $htmlvars
					do
						msgline="$msgline<ulink type=\"http\" url=\"${svnroot}/$j\">$j</ulink> "
					done
					msgline="${msgline}</para>"
					sed -i -e "/<\!-- REVIEW -->/i$msgline" $docdir/$xml
				done
				continue
			fi
			mail=`echo $line|awk '{print $2}'`
			msgline="<para role=\"author\">\n$author <email>$mail</email>\n</para>"
			sed -i -e "/<\!-- AUTHORS -->/i$msgline" $docdir/$xml
		done
	        fi
        done
}

download_source()
{
	msg "正在下载源文件..."
	[ -d $tmpdir ] || mkdir $tmpdir
	pushd $tmpdir >/dev/null
	if [ ! -f $pkgfile ]; then
		wget $source || return 1
	fi
	file="$SRCDEST/$pkgfile"
	local file_type=$(file -bizL "$pkgfile")
	local ext=${file##*.}
	local cmd=''
	case "$file_type" in
		*application/x-tar*)
		cmd="tar" ;;
		*application/x-gzip*)
		case "$ext" in
			gz|z|Z) cmd="gzip" ;;
			*) continue;;
		esac ;;
		*application/x-bzip*)
		case "$ext" in
			bz2|bz) cmd="bzip2" ;;
			*) continue;;
		esac ;;
		*)
		# Don't know what to use to extract this file,
		# skip to the next file
		continue;;
	esac
	local ret=0
	msg2 "正在使用 %s 解压缩文件 %s" "$cmd" "$file"
	if [ "$cmd" = "tar" ]; then
		$cmd -xf "$file" || ret=?
	else
		rm -f "${file%.*}"
		$cmd -dcf "$file" > "${file%.*}" || ret=?
	fi
	if [ $ret -ne 0 ]; then
		error "Failed to extract %s" "$file"
		plain "Aborting..."
		exit 1
	fi
	popd >/dev/null

	init_pot
	init_xmlpot
	init_transifex

	# 合并已翻译po文件内容到源文件
	if [ "$FUZZY" -eq 1 ]; then
		warning "Use fuzzy item -- Unsafe"
		gadt-po -m -f -n $modname -V $pkgver -p . $moddir || return 1
	else
		gadt-po -m -n $modname -V $pkgver -p . $moddir || return 1
	fi

	#更新 xml 模板文件及作者信息
	if [ "$NOUPDATEXML" -eq 0 ]; then
		update_xml
	fi
	gadt-xmlpo -m -L $xml_lang -n $modname -V $pkgver -p . $docdir || return 1
}

compile_source()
{
	msg "正在编译生成新文档..."
	cd $srcdir
	if [ "$NOCONFIGURE" -eq 0 ]; then
		if [ ! -f configure ]; then
			./autogen.sh $configure || return 1
		fi
		./configure $configure || return 1
	fi
	if [ -d $moddir/.libs ]; then
		cd $docdir
	fi
	make || return 1
	cd $startdir
	cp -r $htmldir $tmpdir
	msg "新文档位于 $tmpdir/html"
}

##
# Clean up function. Called automatically when the script exits.
##
clean_up() {
	local EXIT_CODE=$?

	if [ $EXIT_CODE -eq 0 -a "$CLEANUP" -eq 1 ]; then
		# If it's a clean exit and -c/--clean has been passed...
		msg "Cleaning up..."
		rm -rf "$srcdir"
	fi
	if [ $NOBROWSER -eq 0 ];then
		#gvfs-open file://$tmpdir/html/index.html
		firefox file://$tmpdir/html/index.html
	fi
}

##
# Signal Traps
##
trap 'clean_up' 0

make_htmlhelp()
{
	msg "htmlhelp文档为 $modname-$pkgver.tgz"
	cp -r $tmpdir/html $tmpdir/book
	mv $tmpdir/book/*.devhelp2 $tmpdir/book.devhelp
	pushd $tmpdir
	tar -zcf $modname-$pkgver.tgz book book.devhelp
	rm -rf book book.devhelp
	popd >/dev/null
}

make_install()
{
	msg "正在将文档安装到用户目录, 将调用devhelp来显示..."
	if [ ! -d ~/.local/share/gtk-doc/html ];
	then
		mkdir -p ~/.local/share/gtk-doc/html;
	fi

	if [ -d ~/.local/share/gtk-doc/html/$modname ];
	then
		rm -rf ~/.local/share/gtk-doc/html/$modname
	fi
	cp -r $tmpdir/html ~/.local/share/gtk-doc/html/$modname
	PID=$(pidof -o %PPID /usr/bin/devhelp)
	if [ ! -z "$PID" ]; then
		kill $PID
	fi
	devhelp -s "$modname 参考手册" &
}

make_tarball()
{
	msg "正在将文档打包..."
	mkdir -p $tmpdir/$modname-docs-$pkgver
	cat > $tmpdir/$modname-docs-$pkgver/install.sh << MYEOF
#/bin/sh

if [ ! -d ~/.local/share/gtk-doc/html ];
then
	mkdir -p ~/.local/share/gtk-doc/html;
fi

if [ -d ~/.local/share/gtk-doc/html/$modname ];
then
	rm -rf ~/.local/share/gtk-doc/html/$modname
fi
cp -r html ~/.local/share/gtk-doc/html/$modname

MYEOF
	chmod +x $tmpdir/$modname-docs-$pkgver/install.sh
	cp -r $tmpdir/html/ $tmpdir/$modname-docs-$pkgver/
	pushd $tmpdir >/dev/null
	tar zcf $modname-docs-$pkgver.tar.gz $modname-docs-$pkgver
	popd >/dev/null
	rm -rf $tmpdir/$modname-docs-$pkgver/
	msg "文档已打包成功： $tmpdir/$modname-docs-$pkgver.tar.gz"
}

edit_sgml()
{
	if [ -f ~/.gtkdocpo ];then
		username=$(source ~/.gtkdocpo; echo $username)
	else
		username=unknown
	fi

	if [ -f $startdir/AUTHORS -a -d $startdir/docs-$pkgver ]; then
		local sgmls=`cat $startdir/AUTHORS|grep -v "^#"|grep $username |awk '{print $3}'`
		local olddocs=$startdir/docs-$pkgver
		eval $sgmls #这将会产生sgml_files变量
		var=`echo $sgml_files |sed 's/,/ /g'`
		echo $var
		for filename in $var;
		do 
			vim -d $docdir/$filename ${olddocs}/$filename 
		done
	else
		warning "Lost the AUTHORS file or docs-$pkgver directory"
	fi
}

review_all_sgml()
{
	local olddocs=$startdir/$modname-docs
	if [ -d $olddocs ];then
		for f in `find $olddocs -name "*.sgml"`;
		do
			local filename=${f#$olddocs\/}
			vim -d $docdir/$filename ${olddocs}/$filename 
		done
	else
		warning "You have not the $modname-docs"
	fi
}

run_function()
{
	local ret=0
	local func=$1
	#eval `$func 2>&1 | tee "$BUILDLOG"; ret=${PIPESTATUS[0]}`
	if [ "$LOGGING" -eq 1 -a "x$func" = "xcompile_source" ]; then
		BUILDLOG="${tmpdir}/${pkgname}-${pkgver}-build.log"
		if [ -f "$BUILDLOG" ]; then
			local i=1
			while true; do
				if [ -f "$BUILDLOG.$i" ]; then
					i=$(($i +1))
				else
					break
				fi
			done
			mv "$BUILDLOG" "$BUILDLOG.$i"
		fi

		#eval "$func 2>&1 | tee \"$BUILDLOG\"; ret=${PIPESTATUS[0]}"
		eval "$func 2>&1 > $BUILDLOG || ret=$?"
	if [ $ret -gt 0 ]; then
		echo "run $func error."
		exit 2
	fi
	else
		eval "$func 2>&1 || ret=$?"
	fi

	if [ $ret -gt 0 ]; then
		error "Build Failed."
		plain "Aborting..."
		exit 2 # $E_BUILD_FAILED
	fi
}

if [ "$CLEANCACHE" -eq 1 ]; then
	msg "Cleaning up ALL files from %s." "$SRCDEST"
	echo -n "    Are you sure you wish to do this? "
	echo -n "[Y/n]"
	read answer
	answer=$(echo $answer | tr '[:lower:]' '[:upper:]')
	if [ "$answer" = "YES" -o "$answer" = "Y" ]; then
		rm "$SRCDEST"/*
		if [ $? -ne 0 ]; then
			error "Problem removing files; you may not have correct permissions in %s" "$SRCDEST"
			exit 1
		else
			msg "Source cache cleaned."
			exit 0
		fi
	else
		# answer = no
		msg "No files have been removed."
		exit 0
	fi
fi

if [ "$INSTALL" -eq 1 ]; then
	if [ -d $tmpdir/html ]; then
		run_function make_install
		exit 0
	fi
fi

if [ "$TARBALL" -eq 1 ]; then
	if [ -d $tmpdir/html ]; then
		run_function make_tarball
		exit 0
	fi
fi

if [ "$NOEXTRACT" -eq 1 ]; then
	warning "Skipping source retrieval        -- using existing $srcdir tree"

	if [ "$NOEXTRACT" -eq 1 -a -z "$(ls "$srcdir" 2>/dev/null)" ]; then
		error "The source directory is empty, there is nothing to build!"
		plain "Aborting..."
		exit 1
	fi
else
	run_function download_source
fi

if [ "$MERGEPO" -eq 1 ]; then
	run_function merge_pot
	run_function merge_xmlpot
	exit 0;
fi

if [ "$EDITSGML" -eq 1 ]; then
	run_function edit_sgml
	exit 0;
fi

#if [ "$UPDATEXML" -eq 1 ]; then
#	run_function update_xml
#fi

if [ "$REVIEWALLSGML" -eq 1 ]; then
	run_function review_all_sgml
	exit 0;
fi

if [ "$NOBUILD" -eq 0 ]; then
	run_function compile_source
fi

if [ "$NOHTMLHELP" -eq 0 ]; then
	run_function make_htmlhelp
fi

if [ "$INSTALL" -eq 1 ]; then
	run_function make_install
fi
